package com.tsd.jxc.sale.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.core.annotation.CheckBind;
import com.tsd.core.annotation.DataPermission;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.fin.job.JxcFinanceJob;
import com.tsd.jxc.req.JxcSaleReturnBillReqParamsVo;
import com.tsd.jxc.sale.entity.JxcSaleReturnBillDetailExt;
import com.tsd.jxc.sale.entity.JxcSaleReturnBillExt;
import com.tsd.jxc.sale.service.JxcSaleReturnBillService;
import com.tsd.jxc.setting.service.JxcSettingService;
import com.tsd.jxc.utils.JxcAutoApprovalUtil;
import com.tsd.jxc.vo.JxcSettingVo;
import com.tsd.jxc.vo.PrintVo;
import com.tsd.system.controller.SystemBaseController;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：JxcSaleReturnBill销售退货单 控制层
 *
 * @author Hillpool
 * @date 2022/07/29 15:04:27
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "进销存-销售退货单", description = "销售退货单的API描述")
public class JxcSaleReturnBillController extends SystemBaseController {

    @Resource
    private JxcSaleReturnBillService jxcSaleReturnBillService;
    @Resource
    private JxcFinanceJob jxcFinanceJob;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private JxcSettingService jxcSettingService;

    @ApiOperation(value = "根据sid获取销售退货单", notes = "根据sid获取销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "销售退货单sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getJxcSaleReturnBillBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcSaleReturnBillBySid() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcSaleReturnBillExt billExt = jxcSaleReturnBillService.queryBySid(sid);
            if (billExt != null) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                setting.procDisplay(billExt, GlobalSetting.TYPE_CLIENT);
                List<JxcSaleReturnBillDetailExt> detailExtList = billExt.getDetail_list();
                if (!HlpUtils.isEmptyList(detailExtList)) {
                    ListUtil.forEach(detailExtList, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
                    billExt.setDetail_list(detailExtList);
                }
            }
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                hr.setData(JxcSaleReturnBillReqParamsVo.transfer(billExt, settingVo));
            } else {
                hr.setData(billExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除销售退货单", notes = "根据id删除销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "销售退货单sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteJxcSaleReturnBills.action", method = RequestMethod.POST)
    public HttpResult<String> deleteJxcSaleReturnBills() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            jxcSaleReturnBillService.deleteJxcSaleReturnBills(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存销售退货单", notes = "保存销售退货单，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "销售退货单", required = true, paramType = "body", dataType = "JxcSaleReturnBill")
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcSaleReturnBill.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> saveJxcSaleReturnBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcSaleReturnBillReqParamsVo paramsVo = super.getParams(request, JxcSaleReturnBillReqParamsVo.class);
            JxcSaleReturnBillExt billExt = paramsVo.convert();
            jxcSaleReturnBillService.saveJxcSaleReturnBill(billExt, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval("auto_approval_sale_return", () -> {
                jxcSaleReturnBillService.changeJxcSaleReturnBillAuditState(Collections.singletonList(billExt.getSid()), 1, opUser);
            });
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询销售退货单", notes = "分页查询销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcSaleReturnBills.action", method = RequestMethod.POST)
    @DataPermission(code = "saleReturn")
    public HttpResult<Object> findJxcSaleReturnBills() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, null);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "client_sid", "client_sid", false, false);
            HlpUtils.copyStringValue(map, params, "client_name", "client_name", false, false);
            HlpUtils.copyStringValue(map, params, "office_contract_name", "office_contract_name", false, false);
            HlpUtils.copyStringValue(map, params, "sale_order_code", "sale_order_code", false, false);
            HlpUtils.copyDateRangeValue(map, params, "return_date", false);
            PageBean page = new PageBean(map);
            List<JxcSaleReturnBillExt> list = jxcSaleReturnBillService.findJxcSaleReturnBills(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询销售退货单", notes = "分页查询销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcSaleReturnBillsIncludeDetail.action", method = RequestMethod.POST)
    public HttpResult<Object> findJxcSaleReturnBillsIncludeDetail() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, null);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "client_name", "client_name", false, false);
            HlpUtils.copyStringValue(map, params, "office_contract_name", "office_contract_name", false, false);
            HlpUtils.copyStringValue(map, params, "sale_order_code", "sale_order_code", false, false);
            HlpUtils.copyDateRangeValue(map, params, "return_date", false);
            PageBean page = new PageBean(map);
            List<JxcSaleReturnBillExt> list = jxcSaleReturnBillService.findJxcSaleReturnBillsIncludeDetail(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 审核/反审核
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeJxcSaleReturnBillAuditState.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<String> changeJxcSaleReturnBillAuditState() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            return jxcSaleReturnBillService.changeJxcSaleReturnBillAuditState(sidList, state, opUser);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成入库单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcSaleReturnBill2InBill.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> genJxcSaleReturnBill2InBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcSaleReturnBillService.genJxcSaleReturnBill2InBill(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成对账
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcFinanceAccountDetail4SaleReturn.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> genJxcFinanceAccountDetail4SaleReturn() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            Integer genNum = jxcSaleReturnBillService.genJxcFinanceAccountDetail4SaleReturn(sidList, opUser);
            jxcFinanceJob.addAccountSet2PriorityQueue4Finance(DataSourceContextHolder.getDataSourceType());
            hr.setData(genNum);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取销售退货单数据", notes = "打印获取销售退货单数据")
    @ResponseBody
    @RequestMapping(value = "/queryJxcSaleReturnBillData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryJxcSaleReturnBillData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcSaleReturnBillExt> list = jxcSaleReturnBillService.queryJxcSaleReturnBillData4Print(sidList);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
